package br.unisul.prolinear.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.rtf.RTFEditorKit;


public class Util {

	public static void redirect(String page) {
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect(page);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void erro(String msg){
		FacesContext.getCurrentInstance().addMessage("",new FacesMessage(FacesMessage.SEVERITY_ERROR, msg,""));
	}

	public static void msg(String msg){
		FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, msg,""));
	}

	public static String getParametro(String parametro){
		return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(parametro);
	}

	public static <T extends Object> List<T> appendLists(List<T>... listas){
		List<T> nova = new ArrayList<T>();
		for(List<T> lista:listas){
			for(T obj:lista){
				if(!nova.contains(obj)){
					nova.add(obj);
				}
			}
		}
		return nova;
	}

	public static String hashMD5(String text){
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			BigInteger hash = new BigInteger(1, md.digest(text.getBytes()));  
			return  hash.toString(16);
		} catch (NoSuchAlgorithmException e) {			
			e.printStackTrace();
			return null;
		}		   
	}

	public static boolean isValidMail(String email){
		Pattern padrao = Pattern.compile("[a-zA-Z0-9\\_\\-\\.]+@[a-zA-Z0-9\\_\\-]+(\\.[a-zA-Z]+){1,3}");
		Matcher match = padrao.matcher(email);
		return match.matches();
	}

	public static String rftToPlain(String rtf){		
		try {
			RTFEditorKit editor = new RTFEditorKit();			
			Document document = editor.createDefaultDocument();
			editor.read(new ByteArrayInputStream(rtf.getBytes()), document, 0);
			String text = document.getText(0, document.getLength());
			return text;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

}
